package com.hishop.common.interceptor;

import com.google.common.collect.Maps;
import com.hishop.common.Constant;
import com.hishop.common.ServerResponse;
import com.hishop.pojo.User;
import com.hishop.util.CookieUtil;
import com.hishop.util.JsonUtil;
import com.hishop.util.RedisPoolUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.Map;

/**
 * 自定义拦截器
 * Created by hejie on 2018/3/19.
 */
@Slf4j
public class AuthorityInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        log.info("preHandle");
        HandlerMethod handlerMethod = (HandlerMethod) handler;
        String methodName = handlerMethod.getMethod().getName();
        String className = handlerMethod.getBean().getClass().getSimpleName();
        //解析参数，具体的参数key以及value
        StringBuffer sb = new StringBuffer();
        Map<String, String[]> paramMap = request.getParameterMap();
        for (Map.Entry<String, String[]> entry : paramMap.entrySet()) {
            String mapKey = entry.getKey();
            String mapValue = Arrays.toString(entry.getValue());
            sb.append(mapKey).append("=").append(mapValue);
        }
        if (StringUtils.equals(className,"UserManageController") && StringUtils.equals(methodName,"login")){
            return true;//放行
        }
        //打印请求日志,便于排查问题
        log.info("className:{},methodName:{},requestParam:{}",className,methodName,sb.toString());
        User user = null;
        String loginToken = CookieUtil.readLoginToken(request);
        if (!StringUtils.isBlank(loginToken)) {
            String userJson = RedisPoolUtil.get(loginToken);
            user = JsonUtil.string2Obj(userJson, User.class);
        }
        if (user == null || (user.getRole().intValue() != Constant.Role.ROLE_ADMIN)) {
            response.reset();
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/json;charset=UTF-8");
            PrintWriter out = response.getWriter();
            //由于富文本编辑器的返回格式的要求而特殊处理
            if (user == null) {
                if (StringUtils.equals(className,"ProductManageController") && StringUtils.equals(methodName,"richTextUpload")){
                    Map resultMap= Maps.newHashMap();
                    resultMap.put("success",false);
                    resultMap.put("msg","请登录管理员");
                    out.print(JsonUtil.obj2String(resultMap));
                }else
                out.print(JsonUtil.obj2String(ServerResponse.createByErrorMessage("拦截器已拦截，用户未登录!")));
            }
            if (user.getRole().intValue() != Constant.Role.ROLE_ADMIN) {
                if (StringUtils.equals(className,"ProductManageController") && StringUtils.equals(methodName,"rich_text_upload")){
                    Map resultMap= Maps.newHashMap();
                    resultMap.put("success",false);
                    resultMap.put("msg","需要管理员权限操作");
                    out.print(JsonUtil.obj2String(resultMap));
                }else
                out.print(JsonUtil.obj2String(ServerResponse.createByErrorMessage("拦截器已拦截，用户无权限!")));
            }
            out.flush();
            out.close();
            return false;
        }

        return true; //false代表不进入接口，true代表进入接口。
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        log.info("postHandle");//接口方法完成后进入
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        log.info("afterCompletion");//postHandle执行完后进入
    }
}
